package org.spring.springboot.web;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.ibatis.annotations.Param;
import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.spring.springboot.model.BaiduEntity;
import org.spring.springboot.model.InterLink;
import org.spring.springboot.util.enums.ApiUrl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;


@RestController
public class ValidateController {
	
	@RequestMapping(value = "/validate/urls",method = RequestMethod.POST)
	public List<InterLink> validate(@Param("urls")String urls){
		String urlArray[] = urls.split("\n");
	 	List<InterLink> list = new ArrayList<InterLink>();
	 	for (String url : urlArray) {
	 		Response response = null;
	 		boolean timeout = false;
	 		try {
	 			Connection connection = null;
	 			if (url.contains("http")) {
	 				connection = Jsoup.connect(url);
				}else{
					connection = Jsoup.connect("http://"+url);
				}
	 			trustAllHosts();
	 			connection.header("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)");
				response = connection.timeout(10000).execute();
				
			} catch (Exception e) {
				timeout = true;
				e.printStackTrace();
				
			}
	 		InterLink il = new InterLink();
	 		if(response != null && response.statusCode()==200){
	 			Document d = null;
	 			Elements es = null;
				try {
					d = response.parse();
					es = d.select("title");
					System.out.println(url);
					String title = "--";
					if(es.size()>0){
						title = es.get(0).text();
					}
					il.setState("有效");
					il.setTitle(title);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		 			
	 		}else{
	 			il.setTitle("--");
	 			if (timeout) {
	 				il.setState("链接超时");
				}else{
					il.setState("失效");
				}
	 		}
	 		il.setInclude(whetherInclude(url));
	 		il.setUrl(url);
	 		il.setIncludeUrl(ApiUrl.BAIDU.getText()+url);
	 		list.add(il);
		}
		 	
	 	return list;
	}
	
	private String whetherInclude(String url){
		String result = "未收录";
		Connection connection = null;
		Response response = null;
		if (url.endsWith("/#")) {
			url = url.substring(0, url.indexOf("/#"));
		}
		try {
			connection = Jsoup.connect(ApiUrl.BAIDU.getText() + url + "&tn=json");
			connection.header("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)");
			response = connection.ignoreContentType(true).timeout(10000).execute();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (response != null) {
			//System.out.println(response.body());
			String body = response.body();
			JSONObject json = null;
			try {
				json = JSONObject.parseObject(body);
			} catch (Exception e) {
				e.printStackTrace();
				return result;
			}
			String feed = json.get("feed")==null?null:json.get("feed").toString();
			if (feed != null) {
				BaiduEntity entity = JSONObject.parseObject(feed,BaiduEntity.class);
				//System.out.println(entity.getRequestUrl());
				//System.out.println(entity.getEntry().size());
				if (entity.getEntry().size() > 1) {
					if (url.equals(entity.getEntry().get(0).getUrl())) {
						result = "已收录";
					}
				}
			}
		}
		
		return result;
	}
	
	/*Element e = document.body();
			String num = e.select(".nums").text();
			if (num != null && num.contains(ApiUrl.BAIDU_NUM.getText())) {
				num = num.substring(num.indexOf(ApiUrl.BAIDU_NUM.getText())+1,num.indexOf("个"));
				System.out.println(num);
				Integer flag = 0;
				try {
					flag = Integer.parseInt(num);
				} catch (NumberFormatException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if (flag > 0) {
					result = "已收录";
				}
				
			}*/
	
	private static void trustAllHosts() {  
        // Create a trust manager that does not validate certificate chains  
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {  
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
                return new java.security.cert.X509Certificate[] {};  
            }  
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
            }  
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
            }  
        } };  
        // Install the all-trusting trust manager  
        try {  
            SSLContext sc = SSLContext.getInstance("TLS");  
            sc.init(null, trustAllCerts, new java.security.SecureRandom());  
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
	
}
